package com.me.chat.ws;

import com.alibaba.fastjson.JSON;
import com.me.chat.mq.sender.WsChatSender;
import com.me.chat.pojo.chat.ChatMessage;
import com.me.chat.pojo.chat.MessageType;
import com.me.chat.pojo.chat.qo.ChatMessageQO;
import com.me.chat.pojo.relation.SingleRelation;
import com.me.chat.pojo.relation.SingleRelationReq;
import com.me.chat.pojo.relation.qo.SingleRelationReqQO;
import com.me.chat.service.chat.ChatLateService;
import com.me.chat.service.chat.ChatMessageService;
import com.me.chat.util.CommonUtil;
import com.me.chat.util.SimpleUserInfo;
import com.me.chat.util.stauts.MessageCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.time.LocalDateTime;

/**
 * @Authhor: qiu
 * @Date: 2021/12/27 2:55 下午
 */
@Component
@Slf4j
public class WsAction {

    // 用户信息获取
    @Autowired
    private SimpleUserInfo simpleUserInfo;

    //mq topic分发
    @Autowired
    private WsChatSender wsChatSender;

    // 消息服务层
    @Autowired
    private ChatMessageService chatMessageService;

    // 最近联系人服务层
    @Autowired
    private ChatLateService chatLateService;

    public void doAction(Session senderSession, String message,String token) {
        //得到message 该消息会拿来入库与分发
        MessageType messageType = JSON.parseObject(message, MessageType.class);

        int code = messageType.getStatusCode();

        //根据不同的code执行不同的操作
        switch (code) {
            //200 点对点消息传输处理
            case MessageCode.SINGLE_CHAT:
                this.doSingleChat(senderSession, messageType, token);
                break;
            //201 好友关联请求传输处理
            case MessageCode.SINGLE_RELATION_REQ:
                this.doSingleRelationReq(messageType,token);
                break;
            //202 好友关联创建完毕传输请求
            case MessageCode.SINGLE_RELATION:
                this.doSingleRelation(messageType,token);
                break;
            default:
                log.warn("未知的消息类型");
        }
    }

    /**
     * 点对点消息处理
     * @param senderSession
     * @param messageType
     * @param token
     */
    private void doSingleChat(Session senderSession,MessageType messageType,String token) {

        //消息入库 在这个文件中消息入库，是因为当分发失败当时候，也push消息，但是是未发送状态，可以重发
        ChatMessage chatMessage = messageType.getChatMessage();

        String userId = simpleUserInfo.getUserId(token);
        //发送者的id从token中获取
        chatMessage.setSenderId(userId);
        chatMessage.setCreatedTime(LocalDateTime.now());
        //赋值拷贝
        ChatMessageQO chatMessageQO = CommonUtil.copyObject(chatMessage, ChatMessageQO.class);

        //给自己发一份
        try {
            //将set出senderId的消息在变成json字符串
            String afterMessage = JSON.toJSONString(messageType);

            senderSession.getBasicRemote().sendText(afterMessage);
            //topic分发，找到对应的接受者
            wsChatSender.sender(afterMessage);

            //消息入库
            chatMessageService.addChatMessage(chatMessageQO);
            int targetType = chatMessageQO.getTargetType();

            //如果是点对点
            if(targetType == 1) {
                //最新联系人入库
                chatLateService.addChatLately(chatMessageQO);
            }

        } catch (Exception e) {
            e.printStackTrace();
            //异常数据入库，目前无这个状态
        }
    }

    /**
     * 关联请求处理
     * @param messageType
     * @param token
     */
    private void doSingleRelationReq(MessageType messageType,String token) {
        SingleRelationReq singleRelationReq = messageType.getSingleRelationReq();
        //从token中获取到userId
        String userId = simpleUserInfo.getUserId(token);
        singleRelationReq.setCreatedTime(LocalDateTime.now());
        singleRelationReq.setSenderId(userId);

        //无需在这里入库，前台已经先行进行了入库了
        String afterMessage = JSON.toJSONString(messageType);

        //topic分发，找到对应的接受者
        wsChatSender.sender(afterMessage);
    }

    /**
     * 好友关联创建后通知
     * @param messageType
     * @param token
     */
    private void doSingleRelation(MessageType messageType,String token){

        SingleRelation singleRelation = messageType.getSingleRelation();

        //从token中获取到userId 不过这个userId是用做于target的
        String userId = simpleUserInfo.getUserId(token);
        singleRelation.setCreatedTime(LocalDateTime.now());
        singleRelation.setOwnerId(userId);

        //重新json化成字符串
        String afterMessage = JSON.toJSONString(messageType);
        //topic分发，找到对应的接受者
        wsChatSender.sender(afterMessage);

    }
}
